import smtplib
from email.mime.text import MIMEText
from socket import gethostname

class Mailer(object):
    def __init__(self, config):
        self.config = config

        if config['smtp_auth'] == 'tls':
            self.mail_func = self.send_tls
            self.smtp = smtplib.SMTP(
                config['smtp_host'],
                config['smtp_port'])
                
        elif config['smtp_auth'] == 'ssl':
            self.mail_func = self.send_ssl
            self.smtp = smtplib.SMTP_SSL(
                config['smtp_host'],
                config['smtp_port'])

        else:
            self.mail_func = self.send_plain
            self.smtp = smtplib.SMTP(
                config['smtp_host'],
                config['smtp_port'])

    def send(self, updates):
        msg = self.build_msg(updates)
        self.mail_func(msg)

    def send_tls(self, msg):
        self.smtp.ehlo()
        self.smtp.starttls()
        self.smtp.login(self.config['smtp_user'], self.config['smtp_pass'])
        self.smtp.sendmail(self.config['sender'], 
                           self.config['recipient'],
                           msg)
        self.smtp.quit()

    def send_ssl(self, msg):
        pass

    def send_plain(self, msg):
        self.smtp.ehlo()
        self.smtp.sendmail(self.config['sender'],
                           self.config['recipient'],
                           msg)
        self.smtp.quit()

    def build_msg(self, updates):
        text = "The following updates are available:\n\n"

        for pkg in updates:
            if self.config['changelog']:
                text += "============================================================\n"
            text += "** %s (%s -> %s)\n" % (pkg['package'], 
                                            pkg['installed'], 
                                            pkg['version'])
            if self.config['description']:
                text += "   %s\n\n" % pkg['description']
            if self.config['changelog']:
                text += "%s\n\n" % (pkg['changelog'])

        text += "\n(This message was generated by PacMail.)\n"

        msg = MIMEText(text)
        msg['Subject'] = '[%s] %d updates available' % (gethostname(), len(updates))
        msg['From'] = self.config['sender']
        msg['To'] = self.config['recipient']
        return msg.as_string()
